package org.xyl.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.xyl.router.ToolRouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * MCP协议层控制器 - 处理JSON-RPC请求
 */
@RestController
public class McpProtocolController {
    
    private static final Logger logger = LoggerFactory.getLogger(McpProtocolController.class);
    
    @Autowired
    private ToolRouter toolRouter;
    
    @PostMapping("/api/mcp")
    public Map<String, Object> handleJsonRpcRequest(@RequestBody Map<String, Object> request) {
        try {
            // 验证JSON-RPC请求格式
            if (!request.containsKey("jsonrpc") || !request.containsKey("method") || !request.containsKey("id")) {
                return createErrorResponse(request.get("id"), -32600, "无效的JSON-RPC请求格式");
            }
            
            String method = request.get("method") instanceof String ? (String) request.get("method") : "";
            Map<String, Object> params = new HashMap<>();
            if (request.containsKey("params") && request.get("params") instanceof Map) {
                // 安全地转换params并处理类型
                Map<?, ?> rawParams = (Map<?, ?>) request.get("params");
                for (Map.Entry<?, ?> entry : rawParams.entrySet()) {
                    if (entry.getKey() instanceof String) {
                        params.put((String) entry.getKey(), entry.getValue());
                    }
                }
            }
            
            logger.info("接收到MCP请求: method={}, params={}", method, params);
            
            // 使用工具路由处理请求
            Object result = toolRouter.executeTool(method, params);
            
            // 返回成功响应
            return createSuccessResponse(request.get("id"), result);
            
        } catch (IllegalArgumentException e) {
            logger.error("工具调用错误: {}", e.getMessage());
            return createErrorResponse(request.get("id"), -32601, e.getMessage());
        } catch (Exception e) {
            logger.error("服务器内部错误", e);
            return createErrorResponse(request.get("id"), -32603, "服务器内部错误: " + e.getMessage());
        }
    }
    
    private Map<String, Object> createSuccessResponse(Object id, Object result) {
        Map<String, Object> response = new HashMap<>();
        response.put("jsonrpc", "2.0");
        response.put("id", id);
        response.put("result", result);
        return response;
    }
    
    private Map<String, Object> createErrorResponse(Object id, int code, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("jsonrpc", "2.0");
        response.put("id", id);
        
        Map<String, Object> error = new HashMap<>();
        error.put("code", code);
        error.put("message", message);
        response.put("error", error);
        
        return response;
    }
}
